package com.yz.test.parking.sign;


import com.alipay.api.internal.util.StreamUtil;
import com.alipay.api.internal.util.codec.Base64;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * @author shanchong
 * @date 2019-08-07
 **/
public class RSA2 {

    /**
     * 加密
     * @param content
     * @param privateKey
     * @param charset
     * @return
     */
    public static String sign(String content, String privateKey, String charset) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = StreamUtil.readText(new ByteArrayInputStream(privateKey.getBytes())).getBytes();
            encodedKey = Base64.decodeBase64(encodedKey);
            PrivateKey priKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
            Signature signature = Signature.getInstance("SHA256WithRSA");
            signature.initSign(priKey);
            if (StringUtils.isEmpty(charset)) {
                signature.update(content.getBytes());
            } else {
                signature.update(content.getBytes(charset));
            }

            byte[] signed = signature.sign();
            return new String(Base64.encodeBase64(signed));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 验证
     * @param content
     * @param sign
     * @param publicKey
     * @param charset
     * @return
     */
    public static boolean verify(String content, String sign, String publicKey, String charset) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            StringWriter writer = new StringWriter();
            StreamUtil.io(new InputStreamReader(new ByteArrayInputStream(publicKey.getBytes())), writer);
            byte[] encodedKey = writer.toString().getBytes();
            encodedKey = Base64.decodeBase64(encodedKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            Signature signature = Signature.getInstance("SHA256WithRSA");
            signature.initVerify(pubKey);
            if (com.alipay.api.internal.util.StringUtils.isEmpty(charset)) {
                signature.update(content.getBytes());
            } else {
                signature.update(content.getBytes(charset));
            }
            return signature.verify(Base64.decodeBase64(sign.getBytes()));
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        }
    }

}
